package com.fangmou.ing.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by IntelliJ IDEA.
 * User: liming
 * Date: 2010-4-11
 * Time: 18:48:35
 * To change this template use File | Settings | File Templates.
 */
public class DebugUtils {
    /**
     * 以字符串形式返回对象的属性
     * @param object
     * @return
     */
    public static String pojoToString(Object object) {
        if(null == object)
            return "对象未初始化";
        if(object.getClass().isPrimitive() || object.getClass().getPackage().getName().equals("java.lang"))
            return object.toString();
        StringBuffer buff = new StringBuffer();
        Method[] m = object.getClass().getMethods();
        final int idx = 3;
        buff.append(object.toString()+":{");
        try {
            for (int i = 0; i < m.length; i++) {
                String methodName = m[i].getName();
                if (methodName.startsWith("get") && !methodName.endsWith("Class")) {
                    Object o = m[i].invoke(object, new Object[]{});
                    if (o != null) {
                        buff.append(methodName.substring(idx)).append(":").append(o).append(",");
                    }
                }
            }
        } catch (IllegalAccessException iae) {
            iae.printStackTrace();
        } catch (
                InvocationTargetException ite) {
            ite.printStackTrace();
        }
        buff.append("}");
        return buff.toString().replace(",}","}");
    }

    /**
     * 以字符串形式返回数组对象
     * @param objects 数组对象
     * @return
     */
    public static String arrayToString(Object[] objects) {
        if(null == objects || objects.length < 1)
            return "数组对象未初始化";
        StringBuffer buff = new StringBuffer("[");
        for(int i = 0; i < objects.length; i++){
            buff.append(pojoToString(objects[i])).append(",");
        }
        buff.append("]");
        return buff.toString().replace(",]","]");
    }
}
